package com.jh.user.business.impl;

import cn.jh.common.exception.ServiceException;
import cn.jh.common.utils.CommonConstants;
import com.jh.user.business.UserLoginRegisterBusiness;
import com.jh.user.pojo.*;
import com.jh.user.pojo.enums.PayType;
import com.jh.user.repository.*;
import com.jh.user.service.update.pojo.UserOld;
import com.jh.user.service.update.repository.UserOldRepository;
import com.jh.user.util.ObjectUtils;
import com.jh.user.util.Util;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.net.URI;
import java.util.*;

@Service
public class UserLoginRegisterBusinessImpl implements UserLoginRegisterBusiness {

	private static final Logger LOG = LoggerFactory.getLogger(UserLoginRegisterBusinessImpl.class);

	@Autowired
	private UserRepository userRepository;

	// 商铺管理
	@Autowired
	private UserShopsRepository userShopRepository;

	// TODO： 这里有问题，这个接口的包是 com.jh.user.service.update.repository
	//
	@Autowired
	private UserOldRepository userOldRepository;

	@Autowired
	private BrandRateRepository brandRateRepository;

	@Autowired
	private UserBankInfoRepository userBankInfoRepository;

	@Autowired
	private UserAccountRepository accountRepository;

	@Autowired
	private ChannelRateRepository channelRateRepository;

	@Autowired
	private JdpushHistoryRepository jdpushHistoryRepository;

	@Autowired
	private UserAccountFreezeHistoryRepository userAccountFreezeHistoryRepository;

	@Autowired
	private UserBalanceRepository userBalanceRepository;

	@Autowired
	private UserCoinRepository userCoinRepository;

	@Autowired
	private UserRebateFreezeHistoryRepository userRebateFreezeHistoryRepository;

	@Autowired
	private UserRebateHistoryRepository userRebateHistoryRepository;

	@Autowired
	private UserRoleRepository userRoleRepository;

	@Autowired
	private BrandRepository brandRepository;

	@Autowired
	Util util;

	@Autowired
	private EntityManager em;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Transactional
	@Override
	public User saveUser(User user) {
		Brand brand = brandRepository.findBrandByid(user.getBrandId());
		UserOld model = new UserOld();
		if ("6".equals(brand.getBrandType())) {
			user = userRepository.save(user);
		} else {
			user = userRepository.save(user);
			BeanUtils.copyProperties(user, model);
		}
		em.flush();
		return user;
	}

    @Override
    public User queryUserByPhoneAndPassword(String phone,String passWord){
	    return userRepository.findUserByPhoneAndPassword(phone,passWord);
    }

	/** 判断是否登陆 */
	@Override
	public User isValidUser(String phone, String password, long brandId,String deviceId,String source) {
		User user = userRepository.findUserByPhone(phone);
		user.setDeviceId(deviceId);
		user.setSource(source);
		userRepository.save(user);
		return userRepository.findUserByPhoneAndPassword(phone, password, brandId);
	}

	@Override
	public User queryUserById(long userid) {
		return userRepository.findUserById(userid);
	}

	/** 根据brandid和时间获取当前时间的人数 */
	@Override
	public int queryUserNumByBidandtime(long brandId, Date StartTimeDate, Date endTimeDate) {
		if (brandId == -1) {
			return userRepository.queryUserNumBytime(StartTimeDate, endTimeDate);
		}
		return userRepository.queryUserNumByBidandtime(brandId, StartTimeDate, endTimeDate);
	}

	@Transactional
	@Override
	public User createNewUser(User user) {
		Brand brand = brandRepository.findBrandByid(user.getBrandId());
		UserOld model = new UserOld();
		if ("6".equals(brand.getBrandType())) {
			user = userRepository.save(user);
		} else {
			user = userRepository.save(user);
			BeanUtils.copyProperties(user, model);
			model = userOldRepository.save(model);
		}

		/* 设置账户 */
		UserAccount account = new UserAccount();
		account.setUserId(user.getId());
		account.setBalance(BigDecimal.ZERO);
		account.setFreezeBalance(BigDecimal.ZERO);
		account.setCoin(0);
		account.setFreezerebateBalance(BigDecimal.ZERO);
		account.setRebateBalance(BigDecimal.ZERO);
		accountRepository.save(account);

		/* 设置默认角色 */
		UserRole userRole = UserRole.initUserRole(user.getId(), user.getBrandId());
		userRoleRepository.save(userRole);
		em.flush();
		/*
		 * 推送消息 /v1.0/user/jpush/tset

		String alert = "注册推送";
		String content = user.getPhone() + "已成功注册成为您的下级会员！";
		String btype = "register";
		String btypeval = "";
		/** 获取身份证实名信息
		URI uri = util.getServiceUrl("user", "error url request!");
		String url = uri.toString() + "/v1.0/user/jpush/tset";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userId", user.getPreUserId() + "");
		requestEntity.add("alert", alert + "");
		requestEntity.add("content", content + "");
		requestEntity.add("btype", btype + "");
		requestEntity.add("btypeval", btypeval + "");
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.postForObject(url, requestEntity, String.class);
		*/
		return user;
	}

	@Override
	public User isPaypassValid(long userid, String paypass) {
		User user = new User();
		user = userRepository.findUserByUseridAndPayPass(userid, paypass);
		return user;
	}

	@Override
	@Deprecated
	public User queryUserByPhone(String phone) {
		return userRepository.findUserByPhone(phone);
	}

	/** 根据users的手机号码获取用户 */
	@Override
	public List<User> queryUsersByPhone(String phone) {
		List<User> users = new ArrayList<User>();
		users = userRepository.findUsersByPhone(phone);
		return users;
	}

	@Override
	public List<User> queryUserByBrandId(long brandId) {

		List<User> users = new ArrayList<User>();
		users = userRepository.findUserByBrandId(brandId);
		return users;

	}

	/*** 根据等级和贴牌查询 ***/
	@Override
	public List<User> queryUserByGrade(long brandid, String grade) {
		List<User> users = new ArrayList<User>();
		if (brandid == 0) {
			users = userRepository.queryUserByGrade(grade);
		} else {
			users = userRepository.queryUserByGradeAndBrandId(brandid, grade);
		}

		return users;

	}

	/*** 根据等级和贴牌查询 ***/
	@Override
	public List<User> queryUserByStatus(long brandid, String status) {
		List<User> users = new ArrayList<User>();
		users = userRepository.queryUserByGradeAndStatus(brandid, status);
		return users;
	}

	/*** 贴牌审核状态查询 ***/
	@Override
	public List<User> queryUserByStatus(String status) {
		List<User> users = new ArrayList<User>();
		users = userRepository.queryUserByGradeAndStatus(status);
		return users;
	}

	@Override
	public User queryUserByOpenid(String openid) {
		User user = new User();
		user = userRepository.findUserByOpenid(openid);
		return user;
	}

	/**通过上级用户ID查下级*/
	@Override
	public List<User> findAfterUsers(long userid) {
		return userRepository.findAfterUserById(userid);
	}

	/**按传入条件查下级*/
	/*@Override
	public List<User> findUsersBysqlstr(String sqlstr) {
		Query query =  em.createNativeQuery(sqlstr);
		List<User> list = (List<User>)query.getResultList();
		LOG.info("=====listsize:" + list.size());

		/*for(int i=0;i<list.size();i++) {
			Object[] obj = (Object[]) list.get(i);
			if(obj instanceof User){}
			//使用obj[0],obj[1],obj[2]...取出属性　　　　
		}*/
		/*for (int i = 0; i < list.size(); i++) {
			LOG.info("=====phone:" + list.get(i).getPhone());
			if(list.get(i) instanceof User){
				list.set(i,(User)list.get(i));
				LOG.info("=====phone:" + list.get(i).getPhone());
			}
		}*
		em.clear();
		return list;
	}*/
	/**按传入条件查下级*/
	/*@Override
	public List<User> findUsersBysqlstr(String sqlstr) {

		Query query =  em.createQuery(sqlstr);
		List<User> list = (List<User>)query.getResultList();
		LOG.info("=====listsize:" + list.size());
		em.clear();
		return list;
	}*/
	@Override
	public List<User> findUsersBywhere(long brandId,String preUserPhone,String phone,String fullName,String realNameStatus,String shopsStatus,Date startTime) {
		return userRepository.findAll(where(brandId,preUserPhone,phone,fullName,realNameStatus,shopsStatus,startTime));
	}
	/**按传入条件查下级*/
	@Override
	public Page<User> findUsersBywhere(long brandId,String preUserPhone,String phone,String fullName,String realNameStatus,String shopsStatus,Date startTime,Pageable pageable) {
		return userRepository.findAll(where(brandId,preUserPhone,phone,fullName,realNameStatus,shopsStatus,startTime),pageable);
	}
	private Specification<User> where(final long brandId, final String preUserPhone, final String phone, final String fullName,String realNameStatus,String shopsStatus,Date startTime) {
		return new Specification<User>() {
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();
				if (brandId != -1) {
					predicates.add(cb.equal(root.<String>get("brandId"), brandId));
				}
				if (StringUtils.isNotBlank(preUserPhone)) {
					predicates.add(cb.equal(root.<String>get("preUserPhone"), preUserPhone));
				}
				if (StringUtils.isNotBlank(phone)) {
					predicates.add(cb.like(root.<String>get("phone"), "%" + phone + "%"));
				}
				if (StringUtils.isNotBlank(fullName)) {
					predicates.add(cb.like(root.<String>get("fullname"),"%" + fullName + "%"));
				}
				if (StringUtils.isNotBlank(realNameStatus)) {
					predicates.add(cb.equal(root.<String>get("realnameStatus"), realNameStatus));
				}
				if (StringUtils.isNotBlank(shopsStatus)) {
					predicates.add(cb.equal(root.<String>get("shopsStatus"), shopsStatus));
				}
				if (startTime != null) {
					predicates.add(cb.greaterThan(root.<Date>get("createTime"), startTime));
				}
				return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
			}
		};
	}


	@Override
	public List<User> findInfoUsers(Long[] userIds) {
		List<User> users = new ArrayList<User>();
		users = userRepository.findAfterUserByIds(userIds);
		return users;
	}
	@Override
	public List<User> findUsersByInviteCode(String inviteCode){
		return userRepository.findUsersByInviteCode(inviteCode);
	}

	/** 获取改用户的下级会员 */
	@Override
	public List<User> findInfoUsersPageable(Long[] userIds, Pageable pageable) {
		return userRepository.findAfterUserByIdsPageable(userIds, pageable);
	}

	@Override
	public Page<User> findByPreUserId(Long preUserId, Pageable pageable) {
		return userRepository.findByPreUserId(preUserId, pageable);
	}

	/**
	 * 获取用户信息 phone cardNo银行卡号 brandId通道ID brandname通道名称 fullname全称 realname真名
	 * realnameStatus审核状态
	 ***/
	@Override
	public Map findInfoUserByall(long brandId, String fullname, String realnameStatus, String shopsStatus,
			Date StartTimeDate, Date endTimeDate, Pageable pageable) {
		List<User> users = new ArrayList<User>();
		Map<String, Object> object = new HashMap<String, Object>();

		if (fullname != null && !fullname.equals("")) {
			Page<User> p = userRepository.findAfterUserallByfullname(brandId, fullname, pageable);
			object.put("number", p.getNumber());
			object.put("numberOfElements", p.getNumberOfElements());
			object.put("totalElememts", p.getTotalElements());
			object.put("totalpages", p.getTotalPages());
			users = p.getContent();
			object.put("content", this.findInfoUserByall(users));
			return object;
		}
		if (realnameStatus != null && !realnameStatus.equals("")) {
			Page<User> p = userRepository.findAfterUserallByrealnameStatus(brandId, realnameStatus, pageable);
			object.put("number", p.getNumber());
			object.put("numberOfElements", p.getNumberOfElements());
			object.put("totalElememts", p.getTotalElements());
			object.put("totalpages", p.getTotalPages());
			users = p.getContent();
			object.put("content", this.findInfoUserByall(users));
			return object;

		}
		if (shopsStatus != null && !shopsStatus.equals("")) {
			Page<User> p = userRepository.findAfterUserallByshopsStatus(brandId, shopsStatus, pageable);
			object.put("number", p.getNumber());
			object.put("numberOfElements", p.getNumberOfElements());
			object.put("totalElememts", p.getTotalElements());
			object.put("totalpages", p.getTotalPages());
			users = p.getContent();
			object.put("content", this.findInfoUserByall(users));
			return object;

		}

		if (StartTimeDate != null && endTimeDate != null) {
			Page<User> p = userRepository.findAfterUserallBystartendTime(brandId, StartTimeDate, endTimeDate, pageable);
			object.put("number", p.getNumber());
			object.put("numberOfElements", p.getNumberOfElements());
			object.put("totalElememts", p.getTotalElements());
			object.put("totalpages", p.getTotalPages());
			users = p.getContent();
			object.put("content", this.findInfoUserByall(users));
			return object;
		}
		if (StartTimeDate == null && endTimeDate != null) {
			Page<User> p = userRepository.findAfterUserallByendTime(brandId, endTimeDate, pageable);
			object.put("number", p.getNumber());
			object.put("numberOfElements", p.getNumberOfElements());
			object.put("totalElememts", p.getTotalElements());
			object.put("totalpages", p.getTotalPages());
			users = p.getContent();
			object.put("content", this.findInfoUserByall(users));
			return object;
		}
		if (StartTimeDate != null && endTimeDate == null) {
			Page<User> p = userRepository.findAfterUserallByStartTimeDate(brandId, StartTimeDate, pageable);
			object.put("number", p.getNumber());
			object.put("numberOfElements", p.getNumberOfElements());
			object.put("totalElememts", p.getTotalElements());
			object.put("totalpages", p.getTotalPages());
			users = p.getContent();
			object.put("content", this.findInfoUserByall(users));
			return object;
		}
		Page<User> p = userRepository.findAfterUserall(brandId, pageable);
		object.put("number", p.getNumber());
		object.put("numberOfElements", p.getNumberOfElements());
		object.put("totalElememts", p.getTotalElements());
		object.put("totalpages", p.getTotalPages());
		users = p.getContent();
		object.put("content", this.findInfoUserByall(users));
		return object;

	}

	@Override
	public Map findInfoUserByall(String fullname, String realnameStatus, String shopsStatus, Date StartTimeDate,
			Date endTimeDate, Pageable pageable) {
		List<User> users = new ArrayList<User>();
		Map<String, Object> object = new HashMap<String, Object>();

		if (StringUtils.isNotBlank(fullname)) {
			Page<User> p = userRepository.findAfterUserallByfullname(fullname, pageable);
			object.put("number", p.getNumber());
			object.put("numberOfElements", p.getNumberOfElements());
			object.put("totalElememts", p.getTotalElements());
			object.put("totalpages", p.getTotalPages());
			users = p.getContent();
			object.put("content", this.findInfoUserByall(users));
			return object;
		}
		if (StringUtils.isNotBlank(realnameStatus)) {
			Page<User> p = userRepository.findAfterUserallByrealnameStatus(realnameStatus, pageable);
			object.put("number", p.getNumber());
			object.put("numberOfElements", p.getNumberOfElements());
			object.put("totalElememts", p.getTotalElements());
			object.put("totalpages", p.getTotalPages());
			users = p.getContent();
			object.put("content", this.findInfoUserByall(users));
			return object;

		}
		if (shopsStatus != null && !shopsStatus.equals("")) {
			Page<User> p = userRepository.findAfterUserallByshopsStatus(shopsStatus, pageable);
			object.put("number", p.getNumber());
			object.put("numberOfElements", p.getNumberOfElements());
			object.put("totalElememts", p.getTotalElements());
			object.put("totalpages", p.getTotalPages());
			users = p.getContent();
			object.put("content", this.findInfoUserByall(users));
			return object;

		}
		if (StartTimeDate != null && endTimeDate != null) {
			Page<User> p = userRepository.findAfterUserallBystartendTime(StartTimeDate, endTimeDate, pageable);
			object.put("number", p.getNumber());
			object.put("numberOfElements", p.getNumberOfElements());
			object.put("totalElememts", p.getTotalElements());
			object.put("totalpages", p.getTotalPages());
			users = p.getContent();
			object.put("content", this.findInfoUserByall(users));
			return object;
		}
		if (StartTimeDate == null && endTimeDate != null) {
			Page<User> p = userRepository.findAfterUserallByendTime(endTimeDate, pageable);
			object.put("number", p.getNumber());
			object.put("numberOfElements", p.getNumberOfElements());
			object.put("totalElememts", p.getTotalElements());
			object.put("totalpages", p.getTotalPages());
			users = p.getContent();
			object.put("content", this.findInfoUserByall(users));
			return object;
		}
		if (StartTimeDate != null && endTimeDate == null) {
			Page<User> p = userRepository.findAfterUserallByStartTimeDate(StartTimeDate, pageable);
			object.put("number", p.getNumber());
			object.put("numberOfElements", p.getNumberOfElements());
			object.put("totalElememts", p.getTotalElements());
			object.put("totalpages", p.getTotalPages());
			users = p.getContent();
			object.put("content", this.findInfoUserByall(users));
			return object;
		}
		Page<User> p = userRepository.findAfterUserall(pageable);
		object.put("number", p.getNumber());
		object.put("numberOfElements", p.getNumberOfElements());
		object.put("totalElememts", p.getTotalElements());
		object.put("totalpages", p.getTotalPages());
		users = p.getContent();
		object.put("content", this.findInfoUserByall(users));
		return object;

	}

	/***
	 * 下级会员条件查询
	 **/
	public List<User> findUserInfoByall(Long[] str2, String fullname, String realnameStatus, String grade,
			Date StartTimeDate, Date endTimeDate) {
		List<User> users = new ArrayList<User>();
		if (fullname != null && !fullname.equals("")) {
			users = userRepository.findAfterUserallByfullname(str2, fullname);
			return users;
		}
		if (grade != null && !grade.equals("")) {
			users = userRepository.findAfterUserallByGrade(str2, grade);
			return users;
		}
		if (realnameStatus != null && !realnameStatus.equals("")) {
			users = userRepository.findAfterUserallByrealnameStatus(str2, realnameStatus);
			return users;
		}
		if (StartTimeDate != null && endTimeDate != null) {
			users = userRepository.findAfterUserallBystartendTime(str2, StartTimeDate, endTimeDate);
			return users;
		}
		if (StartTimeDate == null && endTimeDate != null) {
			users = userRepository.findAfterUserallByendTime(str2, endTimeDate);
			return users;
		}
		if (StartTimeDate != null && endTimeDate == null) {
			users = userRepository.findAfterUserallByStartTimeDate(str2, StartTimeDate);
			return users;
		}
		users = userRepository.findAfterUserByIdsu(str2);

		return users;

	}

	public List<InfoUser> findInfoUserByall(List<User> users) {

		List<InfoUser> infoUsers = new ArrayList<InfoUser>();
		StringBuffer sb = new StringBuffer();
		JSONObject authObject = null;
		for (int i = 0; i < users.size(); i++) {
			sb.append(users.get(i).getId());
			if (i != users.size() - 1) {
				sb.append(",");
			}
		}
		JSONObject realNameJson = getRealNameJSONObjectByUserIds(sb.toString());
		JSONObject sumProfitRecoders = getSumProfitByUserIds(sb.toString());
		JSONObject sumType2Json = getSumPayTypeJSONObjectByUserIds(sb.toString(),"2");
		JSONObject sumType0Json = getSumPayTypeJSONObjectByUserIds(sb.toString(),"0");
		for (User user : users) {
			UserBankInfo ubi = userBankInfoRepository.queryDefUserBankInfoByUserid(user.getId());
			UserAccount userAccount = accountRepository.findUserAccountByUserid(user.getId());

			InfoUser infouser = new InfoUser();

			// 系统编号
			infouser.setUserid(user.getId());

			// 用户手机号
			infouser.setPhone(user.getPhone());

			infouser.setFullname(user.getFullname());

			// 用户性别
			infouser.setSex(user.getSex());

			// 商铺状态
			infouser.setUsershopStatus(user.getShopsStatus());
			if (user.getShopsStatus().equals("1")) {

				UserShops uShop = userShopRepository.findUserShopsByUid(user.getId());
				if(uShop == null) return infoUsers;
				infouser.setUserShopName(uShop.getName());
				infouser.setUserShopAddress(uShop.getAddress());
			}
			if (ObjectUtils.isNotEmpty(ubi) && StringUtils.isNotBlank(ubi.getUserName())) {
				infouser.setBankName(ubi.getBankName());
				infouser.setBankName(ubi.getBankName());
				infouser.setCardNo(ubi.getCardNo());
				// 真是姓名
				infouser.setRealname(ubi.getUserName());
				// 身份证号
				infouser.setIdcard(ubi.getIdcard());

			} else {
				//String realNameStatus = user.getRealnameStatus();
				authObject = realNameJson.getJSONObject(user.getId() + "");
				if (authObject != null && !"null".equals(authObject) && !authObject.isNullObject()) {
					// 真实姓名
					infouser.setRealname(StringUtils.isBlank(authObject.getString("realname")) ? "" : authObject.getString("realname"));
					// 身份证号
					infouser.setIdcard(StringUtils.isBlank(authObject.getString("idcard")) ? "" : authObject.getString("idcard"));
				} else {
					infouser.setRealname("");
					infouser.setIdcard("");
				}
			}
			String rechargeSum = "";
			String withdrawSum = "";
			String userSumProfit = "";
			// 实名状态
			if(ObjectUtils.isNotEmpty(user) ){
				infouser.setRealnameStatus(user.getRealnameStatus());
				infouser.setBrandId(user.getBrandId());
				infouser.setBrandName(user.getBrandname());
				try {
					rechargeSum = sumType0Json.getString(user.getId() + "");
				} catch (Exception e1) {
					rechargeSum = "";
				}

				try {
					withdrawSum = sumType2Json.getString(user.getId() + "");
				} catch (Exception e1) {
					withdrawSum = "";
				}
				infouser.setRechargeSum(StringUtils.isBlank(rechargeSum) ? BigDecimal.ZERO : new BigDecimal(rechargeSum));
				infouser.setWithdrawSum(StringUtils.isBlank(withdrawSum) ? BigDecimal.ZERO : new BigDecimal(withdrawSum));

				try {
					userSumProfit = sumProfitRecoders.getString(user.getId() + "");
				} catch (Exception e) {
					userSumProfit = "";
				}
				infouser.setRebateSum(StringUtils.isBlank(userSumProfit) ? BigDecimal.ZERO : new BigDecimal(userSumProfit));
				// 提款费
				BrandRate randRate = brandRateRepository.findBrandRate(user.getBrandId(), 1, user.getUserGrade(), PayType.WITHDRAW.getValue());
				if (ObjectUtils.isNotEmpty(randRate ) && randRate.getExtraFee() != null) {
					infouser.setWithdrawFee(randRate.getExtraFee().setScale(2, BigDecimal.ROUND_DOWN));
				} else {
					infouser.setWithdrawFee(new BigDecimal("2.00"));
				}

				// 级别
				infouser.setGrade(user.getGrade());
				// 注册时间
				infouser.setCreateTime(user.getCreateTime());
			}

			if(ObjectUtils.isNotEmpty(userAccount)){
				infouser.setBalance(userAccount.getBalance());
				infouser.setFreezeBalance(userAccount.getFreezeBalance());
				infouser.setCoin(userAccount.getCoin());
				infouser.setRebateBalance(userAccount.getRebateBalance());
				infouser.setFreezerebateBalance(userAccount.getFreezerebateBalance());
			}
			infoUsers.add(infouser);
		}

		return infoUsers;
	}

	// 优化后
	private JSONObject getRealNameJSONObjectByUserIds(String userIds) {
		URI uri = util.getServiceUrl("paymentchannel", "error url request!");
		String url = uri.toString() + "/v1.0/paymentchannel/realname/findby/userids";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userIds", userIds);
		RestTemplate restTemplate = new RestTemplate();
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		JSONObject jsonObject = JSONObject.fromObject(result);
		return jsonObject.getJSONObject(CommonConstants.RESULT);
	}

	// 优化后
	private JSONObject getSumProfitByUserIds(String acqUserIds) {
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/profit/query/byuserids";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("acqUserIds", acqUserIds);
		RestTemplate restTemplate = new RestTemplate();
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		JSONObject jsonObject = JSONObject.fromObject(result);
		return jsonObject.getJSONObject(CommonConstants.RESULT);
	}
	//	优化后
	private JSONObject getSumPayTypeJSONObjectByUserIds(String userIds,String type){
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/byuserids";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userIds", userIds);
		requestEntity.add("type", type);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		JSONObject jsonObject = JSONObject.fromObject(result);
		return jsonObject.getJSONObject(CommonConstants.RESULT);
	}

	private BigDecimal getSumPayType(long userid, String type) {

		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/userid";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid + "");
		requestEntity.add("type", type);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		JSONObject jsonObject = JSONObject.fromObject(result);
		String resultsum = jsonObject.getString("result");
		if (resultsum != null && !resultsum.equals("") && !resultsum.equalsIgnoreCase("null")) {
			return new BigDecimal(resultsum);
		} else {
			return new BigDecimal("0.00");
		}
	}

	private BigDecimal getSumProfit(long userid) {

		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/profit/query/userid";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("acq_user_id", userid + "");
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		JSONObject jsonObject = JSONObject.fromObject(result);
		String resultsum = jsonObject.getString("result");
		if (resultsum != null && !resultsum.equals("") && !resultsum.equalsIgnoreCase("null")) {
			return new BigDecimal(resultsum);
		} else {
			return new BigDecimal("0.00");
		}
	}

	@Override
	public Long[] queryUserIdByGradeAndBrandId(long brandid, String grade) {

		return userRepository.queryUserIdByGradeAndBrandId(brandid, grade);
	}

	@Override
	public Long[] queryUserIdBypreUserIds(Long[] userIds) {

		return userRepository.queryUserIdBypreUserIds(userIds);
	}

	@Override
	public Long[] queryUserIdBypreUserIdsAndGrade(String grade, Long[] userIds) {

		return userRepository.queryUserIdBypreUserIdsAndGrade(userIds, grade);
	}

	@Override
	public Long[] queryUserIdBypreUserIdsAndrealnameStatus(String realnameStatus, Long[] userIds) {

		return userRepository.queryUserIdBypreUserIdsAndrealnameStatus(userIds, realnameStatus);
	}

	// 根据省市县模糊查询用户信息
	@Override
	public List<User> queryUserByProvince(String province, String city, String county, Pageable pageable) {

		if (province != null && !province.equals("")) {
			if (city != null && !city.equals("")) {
				if (county != null && county.equals("")) {
					return userRepository.queryUserByProvince1(province, city, county, pageable);
				} else {
					return userRepository.queryUserByProvince2(province, city, pageable);
				}
			} else {
				if (county != null && !county.equals("")) {
					return userRepository.queryUserByProvince4(province, county, pageable);
				} else {
					return userRepository.queryUserByProvince5(province, pageable);
				}
			}
		} else {
			if (city != null && !city.equals("")) {
				if (county != null && !county.equals("")) {
					return userRepository.queryUserByProvince3(city, county, pageable);
				} else {
					return userRepository.queryUserByProvince6(city, pageable);
				}
			} else {
				return userRepository.queryUserByProvince7(county, pageable);
			}
		}

	}

	@Override
	public User queryUserByPhoneAndBrandid(String phone, long brandid) {
		User user = new User();
		UserOld model;
		if (brandid == -1) {
			LOG.info("-1进入");
			model = userOldRepository.findUserByPhone(phone);
			if(model!=null){
				BeanUtils.copyProperties(model, user);
			}else{
				user = null;
			}
		} else {
			user = userRepository.findUserByPhoneAndBrandID(phone, brandid);
		}
		em.clear();
		return user;
	}

	@Override
	public int queryBrandUserCount(long brandId) {
		return userRepository.queryCountByBrandId(brandId);
	}

	@Override
	public User queryUserByPhoneBrandid(String phone, long brandid) {
		User user = new User();
		UserOld model;
		if (brandid == -1) {
			LOG.info("-1进入");
			model = userOldRepository.findUserByPhone(phone);
			if(model!=null){
				BeanUtils.copyProperties(model, user);
			}else{
				user = null;
			}
		} else {
			user = userRepository.findUserByPhoneAndBrandID(phone, brandid);
		}
		em.clear();
		return user;
	}

	@Transactional
	@Override
	public User createOutNewUser(User user) {
		Brand brand = brandRepository.findBrandByid(user.getBrandId());
		UserOld model = new UserOld();
		if ("6".equals(brand.getBrandType())) {
			user = userRepository.save(user);
		} else {
			user = userRepository.save(user);
			BeanUtils.copyProperties(user, model);
			model = userOldRepository.save(model);
		}
		UserAccount account = new UserAccount();
		account.setUserId(user.getId());
		account.setBalance(BigDecimal.ZERO);
		account.setFreezeBalance(BigDecimal.ZERO);
		account.setCoin(0);
		account.setFreezerebateBalance(BigDecimal.ZERO);
		account.setRebateBalance(BigDecimal.ZERO);
		accountRepository.save(account);
		return user;
	}
	
	@Override
	public int queryUserAfterTodayCount(long userId, String todayStr) {
		return userRepository.queryUserAfterTodayCount(userId, todayStr);
	}

	@Override
	public int queryUserAfterYesterdayCount(long userId, String yesterday) {
		return userRepository.queryUserAfterYesterdayCount(userId, yesterday);
	}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
	@Transactional
	@Override
	public void delUserByUserid(long userid) {
		accountRepository.delUserAccount(userid);
		userBankInfoRepository.delBankInfoByUserid(userid);
		channelRateRepository.delChannelRateByUserid(userid);
		jdpushHistoryRepository.delJdpushHistoryByUserid(userid);
		userAccountFreezeHistoryRepository.delUserAccountHistoryByUserid(userid);
		userBalanceRepository.delUserBalanceHistoryByUserid(userid);
		userCoinRepository.delUserCoinByUserid(userid);
		userRebateFreezeHistoryRepository.delUserRebateFreeHistoryByUserid(userid);
		userRebateHistoryRepository.delUserRebateHistoryByUserid(userid);
		userRoleRepository.delUserRoleByUserid(userid);
		userShopRepository.delUserShopsByUserid(userid);
	}

	@Transactional
	@Override
	public void delUserByUserId(long userid) {
		Brand brand = brandRepository.findBrandByid(userRepository.findUserById(userid).getBrandId());
		if ("6".equals(brand.getBrandType())) {
			userRepository.delUserByUserid(userid);
		} else {
			userRepository.delUserByUserid(userid);
			userOldRepository.delUserByUserid(userid);
		}
	}

	@Override
	public User findUserByIdAndBrandId(long userId, long brandId) {
		User user = userRepository.queryUserByIdAndBrandId(userId, brandId);
		return user;
	}

	@Override
	public User findUserById(long userId) {
		return userRepository.findUserById(userId);
	}
	
	@Override
	public String findStatusByUserId(long userId) {
		// TODO Auto-generated method stub
		String status = userRepository.queryUserStatusByUserId(userId);
		return status;
	}

	@Transactional
	@Override
	public void updateUserStatusByUserId(long userId) {
		userRepository.updateUserStatusByUserId(userId);
	}

	@Transactional
	@Override
	public void save(User user){

		String sql = "update t_user set pre_user_phone= '" + user.getPreUserPhone() + "' where  phone = '"+user.getPhone()+"' ";
		jdbcTemplate.update(sql);
	}

	/**
	 * 查询用户等级
	 * @param userId
	 * @return
	 */
	public Map queryGrade(long userId){
		String sql = "select t.grade,t.pre_user_id from  t_user t where  t.id = " + userId + " and t.pre_user_id = t.id ";
		SqlRowSet set = jdbcTemplate.queryForRowSet(sql);
		Map map = new HashMap();
		while (set.next()){
			map.put("grade",set.getString("grade"));
			map.put("preUserId",set.getString("pre_user_id"));
		}
		return map;
	}

	/**
	 * 查询贴牌商
	 * @param brandId
	 * @return
	 */
	public Map queryBandId(String brandId){
		String sql = "select t.id,t.pre_user_id,t.brand_id from  t_user t where  t.brand_id = " + brandId + " and t.grade = 2 ";
		SqlRowSet set = jdbcTemplate.queryForRowSet(sql);
		Map map = new HashMap();
		while (set.next()){
			map.put("userId",set.getString("id"));
			map.put("brandId",set.getString("brand_id"));
		}
		return map;
	}

	@Override
	public long findRoleByPhone(String agent) throws ServiceException {
		User user = userRepository.findUserByPhone(agent);
		if (null == user) {
			throw new ServiceException("获取台卡代理的用户信息失败！");
		}
		long id = user.getId();
		UserRole userRole = userRoleRepository.queryUserRole(id);
		if (null == userRole) {
			throw new ServiceException("获取台卡代理的角色信息失败！");
		}
		long roleId = userRole.getRoleId();
		return roleId;
	}

	public long getBrand(long brandId) {
		long brandUserId = 0;
		Brand brand = brandRepository.findBrandByid(brandId);
		try {
			brandUserId = brand.getManageid();
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return brandUserId;
	}

	@Override
	public User getPreUserId(long userId) {
		try {
			User user = userRepository.findUserById(userId);
			return user;
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Map<String, Object> findUserIdByPhone(String phone, long brandId) throws ServiceException {
		Map<String, Object> map = new HashMap<>();

		User exist = userRepository.findByPhoneAndBrandId(phone, brandId);
		if (null == exist) {
			throw new ServiceException("无该用户信息！");
		}
		long userId = exist.getId();

		map.put("userId", userId);
		return map;
	}

	@Override
	public Map<String, Object> findPhoneByUserId(String userIds, long brandId) throws ServiceException {
		Map<String, Object> resMap = new HashMap<>();
		List<Map<String, Object>> list = new ArrayList<>();

		Pageable pageable = new PageRequest(0, 20, new Sort(Sort.Direction.DESC, "createTime"));
		Page<User> userPage = userRepository.findAll(userWhere(userIds, brandId), pageable);
		List<User> content = userPage.getContent();
		if (content.size() == 0) {
			resMap.put("list", list);
		} else {
			for (User user : content) {
				long userId = user.getId();
				String phone = user.getPhone();

				Map<String, Object> map = new HashMap<>();
				map.put("userId", userId);
				map.put("phone", phone);

				list.add(map);
			}
			resMap.put("list", list);
		}
		return resMap;
	}

	@Override
	public Map<String, Object> appFindRoleId(long userId, long brandId) throws ServiceException {
		Map<String, Object> map = new HashMap<>();

		UserRole userRole = userRoleRepository.queryByUserIdAndBrandId(userId, brandId);
		if (null == userRole) {
			throw new ServiceException("为查询到您的角色信息！");
		}
		long roleId = userRole.getRoleId();

		map.put("roleId", roleId);
		return map;
	}

	private Specification<User> userWhere(final String userIds, final long brandId) {
		return (root, criteriaQuery, criteriaBuilder) -> {
			List<Predicate> predicates = new ArrayList<>();

			predicates.add(criteriaBuilder.equal(root.<Long>get("brandId"), brandId));
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(userIds)) {
				CriteriaBuilder.In<Long> inUserId = criteriaBuilder.in(root.<Long>get("id"));
				String[] split = userIds.split(",");
				for (String userIdStr : split) {
					if (org.apache.commons.lang3.StringUtils.isNotBlank(userIdStr)) {
						inUserId.value(Long.parseLong(userIdStr));
					}
				}
				predicates.add(inUserId);
			}
			return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
		};
	}
}
